package com.dawnling.countdownlistdemo.utils;

import android.os.Handler;

import java.util.HashSet;
import java.util.Iterator;

/**
 * 全局单例计时器
 */
public class MyTimer {

    private HashSet<Listener> mSet = new HashSet<>();
    public boolean isLive = false;
    private Thread mThread;
    private Handler mHandler;

    public MyTimer(Handler handler) {
        mHandler = handler;
        if (mHandler == null) {
            mHandler = new Handler();
        }
    }

    public void onStart() {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        isLive = true;
        if (mThread == null) {
            mThread = new Thread() {
                @Override
                public void run() {
                    super.run();
                    while (isLive) {
                        try {
                            Thread.sleep(1000);
                            for (Iterator it = mSet.iterator(); it.hasNext(); ) {
                                if (mHandler != null) {
                                    ((Listener) it.next()).onNextSecond();
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mThread = null;

                }
            };
            mThread.start();
        }
    }

    public void onStop() {
        if (mThread == null) {
            return;
        }
        isLive = false;
    }

    public void add(Listener listener) {
        mSet.add(listener);
        onStart();
    }

    public void remove(Listener listener) {
        mSet.remove(listener);
        if (isEmpty()) {
            onStop();
        }
    }

    /**
     * 是否有线程
     */
    private boolean isEmpty() {
        return mSet.isEmpty();
    }

    public interface Listener {
        void onNextSecond();
    }

}
